package com.etoak.config;

import com.etoak.filter.CrossFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig  implements WebMvcConfigurer {

    @Value("${image.dir}")
    String  uploadDir;


    @Value("${image.path}")
    String  pathPrefix;


    @Bean
    public FilterRegistrationBean <CrossFilter> crossFilter(){
        FilterRegistrationBean<CrossFilter> registrationBean =
                new FilterRegistrationBean<>();
        registrationBean.setFilter(new CrossFilter());

        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //mapping = /files/**
        String mapping = pathPrefix.endsWith("/")?
                StringUtils.join(pathPrefix,"**"):
                StringUtils.join(pathPrefix,"/**");
        //location = file:d:/upload/et2108/
        String  location = uploadDir.endsWith("/")?
                StringUtils.join("file:",uploadDir):
                StringUtils.join("file:",uploadDir,"/");


        registry.addResourceHandler(mapping)
                .addResourceLocations(location);
    }
}
